'use client';

import { useState, useCallback } from 'react';
import { useDropzone } from 'react-dropzone';
import Image from 'next/image';
import Link from 'next/link';
import axios from 'axios';
import { ReactCompareSlider, ReactCompareSliderImage } from 'react-compare-slider';
import Skeleton from 'react-loading-skeleton';
import 'react-loading-skeleton/dist/skeleton.css';

export default function RestorePage() {
  const [originalImage, setOriginalImage] = useState<string | null>(null);
  const [restoredImage, setRestoredImage] = useState<string | null>(null);
  const [isProcessing, setIsProcessing] = useState(false);
  const [error, setError] = useState<string | null>(null);
  const [repairMode, setRepairMode] = useState<string>('general'); // 默认修复模式

  const onDrop = useCallback((acceptedFiles: File[]) => {
    setError(null);
    const file = acceptedFiles[0];
    
    if (!file) return;
    
    // 检查文件类型
    if (!file.type.includes('image')) {
      setError('请上传有效的图片文件');
      return;
    }
    
    // 检查文件大小 (限制为10MB)
    if (file.size > 10 * 1024 * 1024) {
      setError('图片大小不能超过10MB');
      return;
    }
    
    const reader = new FileReader();
    reader.onload = () => {
      setOriginalImage(reader.result as string);
      setRestoredImage(null);
    };
    reader.readAsDataURL(file);
  }, []);

  const { getRootProps, getInputProps, isDragActive } = useDropzone({
    onDrop,
    accept: {
      'image/*': ['.jpeg', '.jpg', '.png', '.webp']
    },
    maxFiles: 1
  });

  const processImage = async () => {
    if (!originalImage) return;
    
    setIsProcessing(true);
    setError(null);
    
    try {
      // 调用我们的API路由，该路由将使用阿里云图像增强服务
      const response = await axios.post('/api/restore', {
        imageUrl: originalImage,
        mode: repairMode
      });
      
      setRestoredImage(response.data.restoredImageUrl);
    } catch (err) {
      console.error('处理图片时出错:', err);
      setError('处理图片时出错，请稍后再试');
    } finally {
      setIsProcessing(false);
    }
    
    // 模拟API调用 (仅用于演示)
    // 实际项目中删除这段代码
    setTimeout(() => {
      setRestoredImage(originalImage);
      setIsProcessing(false);
    }, 2000);
  };

  const downloadRestoredImage = () => {
    if (!restoredImage) return;
    
    const link = document.createElement('a');
    link.href = restoredImage;
    link.download = 'restored-image.jpg';
    document.body.appendChild(link);
    link.click();
    document.body.removeChild(link);
  };

  return (
    <main className="flex min-h-screen flex-col items-center p-6 md:p-24">
      <div className="w-full max-w-5xl">
        <div className="flex items-center mb-8">
          <Link href="/" className="text-blue-600 hover:underline mr-4">
            &larr; 返回首页
          </Link>
          <h1 className="text-3xl font-bold">照片修复</h1>
        </div>
        
        <div className="bg-white/30 p-6 rounded-lg shadow-lg backdrop-blur-sm">
          <div className="mb-8">
            <h2 className="text-xl font-semibold mb-4">第1步：上传照片</h2>
            <div 
              {...getRootProps()} 
              className={`border-2 border-dashed rounded-lg p-8 text-center cursor-pointer transition-colors ${
                isDragActive ? 'border-blue-500 bg-blue-50' : 'border-gray-300 hover:border-blue-400'
              }`}
            >
              <input {...getInputProps()} />
              {isDragActive ? (
                <p>将图片放在这里...</p>
              ) : (
                <div>
                  <p className="mb-2">拖放图片到此处，或点击选择图片</p>
                  <p className="text-sm text-gray-500">支持JPG、PNG和WebP格式</p>
                </div>
              )}
            </div>
            {error && (
              <p className="text-red-500 mt-2">{error}</p>
            )}
          </div>
          
          {originalImage && (
            <div className="mb-8">
              <h2 className="text-xl font-semibold mb-4">第2步：选择修复类型</h2>
              <div className="grid grid-cols-1 sm:grid-cols-3 gap-4 mb-6">
                <div 
                  className={`p-4 border rounded-lg cursor-pointer ${repairMode === 'general' ? 'border-blue-500 bg-blue-50' : 'border-gray-200'}`}
                  onClick={() => setRepairMode('general')}
                >
                  <h3 className="font-medium mb-2">通用修复</h3>
                  <p className="text-sm text-gray-600">适用于大多数老照片，修复划痕和褪色</p>
                </div>
                <div 
                  className={`p-4 border rounded-lg cursor-pointer ${repairMode === 'colorize' ? 'border-blue-500 bg-blue-50' : 'border-gray-200'}`}
                  onClick={() => setRepairMode('colorize')}
                >
                  <h3 className="font-medium mb-2">黑白照片上色</h3>
                  <p className="text-sm text-gray-600">为黑白照片添加自然的色彩</p>
                </div>
                <div 
                  className={`p-4 border rounded-lg cursor-pointer ${repairMode === 'enhance' ? 'border-blue-500 bg-blue-50' : 'border-gray-200'}`}
                  onClick={() => setRepairMode('enhance')}
                >
                  <h3 className="font-medium mb-2">超清增强</h3>
                  <p className="text-sm text-gray-600">提高照片清晰度和细节</p>
                </div>
              </div>
              
              <div className="mb-4">
                <button
                  onClick={processImage}
                  disabled={isProcessing}
                  className={`px-6 py-3 rounded-md ${
                    isProcessing 
                      ? 'bg-gray-400 cursor-not-allowed' 
                      : 'bg-blue-600 hover:bg-blue-700 text-white'
                  }`}
                >
                  {isProcessing ? '处理中...' : '开始修复'}
                </button>
              </div>
              
              <div className="bg-blue-50 border border-blue-200 rounded-lg p-4 text-sm text-blue-800">
                <p className="font-medium mb-1">使用阿里云图像增强服务</p>
                <p>本服务使用阿里云图像增强技术，提供专业的老照片修复、上色和增强功能。</p>
              </div>
            </div>
          )}
          
          {(originalImage || isProcessing) && (
            <div className="mb-8">
              <h2 className="text-xl font-semibold mb-4">预览</h2>
              <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
                <div>
                  <p className="mb-2 font-medium">原始照片</p>
                  {originalImage ? (
                    <div className="relative h-64 md:h-80 bg-gray-100 rounded-lg overflow-hidden">
                      <Image 
                        src={originalImage} 
                        alt="原始照片" 
                        fill
                        style={{ objectFit: 'contain' }}
                      />
                    </div>
                  ) : (
                    <Skeleton height={320} />
                  )}
                </div>
                
                <div>
                  <p className="mb-2 font-medium">修复后的照片</p>
                  {isProcessing ? (
                    <div className="h-64 md:h-80 flex items-center justify-center bg-gray-100 rounded-lg">
                      <div className="text-center">
                        <div className="inline-block animate-spin rounded-full h-8 w-8 border-4 border-blue-500 border-t-transparent"></div>
                        <p className="mt-2">正在修复中...</p>
                      </div>
                    </div>
                  ) : restoredImage ? (
                    <div className="relative h-64 md:h-80 bg-gray-100 rounded-lg overflow-hidden">
                      <Image 
                        src={restoredImage} 
                        alt="修复后的照片" 
                        fill
                        style={{ objectFit: 'contain' }}
                      />
                    </div>
                  ) : (
                    <div className="h-64 md:h-80 flex items-center justify-center bg-gray-100 rounded-lg">
                      <p className="text-gray-500">等待处理...</p>
                    </div>
                  )}
                </div>
              </div>
            </div>
          )}
          
          {restoredImage && (
            <div className="mb-8">
              <h2 className="text-xl font-semibold mb-4">对比效果</h2>
              <div className="h-80 bg-gray-100 rounded-lg overflow-hidden">
                <ReactCompareSlider
                  itemOne={
                    <ReactCompareSliderImage 
                      src={originalImage!}
                      alt="原始照片"
                    />
                  }
                  itemTwo={
                    <ReactCompareSliderImage 
                      src={restoredImage}
                      alt="修复后的照片"
                    />
                  }
                />
              </div>
              
              <div className="mt-6">
                <button
                  onClick={downloadRestoredImage}
                  className="px-6 py-3 bg-green-600 text-white rounded-md hover:bg-green-700"
                >
                  下载修复后的照片
                </button>
              </div>
            </div>
          )}
        </div>
      </div>
    </main>
  );
} 